package util;

import bean.DataPoint;

import java.util.ArrayList;
import java.util.List;

/**
 * @author :chensi
 */
public class SevenPointFunctionV2 {

    public List<DataPoint[]> process(DataPoint[] data, double midValue, Integer continueNum) {
        if (continueNum == null) {
            continueNum = 7;
        }
        List<DataPoint> tmp = new ArrayList<>();
        List<DataPoint[]> result = new ArrayList<>();
        //大于中值为1 小于中值为-1 等于中值为0
        int flag = 0;
        for (int i = 0; i < data.length; i++) {
            if (tmp.isEmpty()) {
                if (data[i].getValue() > midValue) {
                    flag = 1;
                    tmp.add(data[i]);
                } else if (data[i].getValue() < midValue) {
                    flag = -1;
                    tmp.add(data[i]);
                } else {
                    flag = 0;
                }
            } else {
                double difValue = data[i].getValue() - midValue;
                if (difValue > 0) {
                    switch (flag) {
                        case 1:
                            tmp.add(data[i]);
                            break;
                        case 0:
                            addAndClear(tmp, result, continueNum);
                            break;
                        case -1:
                            addAndClear(tmp, result, continueNum);
                            break;
                    }
                } else if (difValue < 0) {
                    switch (flag) {
                        case -1:
                            tmp.add(data[i]);
                            break;
                        case 1:
                            addAndClear(tmp, result, continueNum);
                            break;
                        case 0:
                            addAndClear(tmp, result, continueNum);
                            break;
                    }
                } else {
                    switch (flag) {
                        case 0:
                            tmp.add(data[i]);
                            break;
                        case 1:
                            addAndClear(tmp, result, continueNum);
                            break;
                        case -1:
                            addAndClear(tmp, result, continueNum);
                            break;
                    }
                }
            }
        }
        addAndClear(tmp, result, continueNum);
        return result;
    }

    private void addAndClear(List<DataPoint> tmp, List<DataPoint[]> result, int continueNum) {
        if (tmp.size() >= continueNum) {
            result.add(tmp.toArray(new DataPoint[tmp.size()]));
        }
        tmp.clear();
    }
}
